package cn.tom.controller;

import cn.tom.tools.*;
import cn.tom.entity.*;
import cn.tom.service.*;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/api/public")
@Slf4j
public class PublicController {
    @Resource
    private LargeFileService largeFileService;
    @Resource
    private UserService userService;
    @Resource
    private HotService hotService;
    @Resource
    private  TypeService typeService;
    @Resource
    private  BookService bookService;
    @Resource
    private  CartService cartService;
    @Resource
    private CommentService commentService;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    SmsService smsService;


    @GetMapping("/captcha")
    //短信验证接口 ： 获取发送验证码
    public XJson smsCode(String phone){
        boolean b = smsService.smsVerifyCode(phone);
        if (b){
           return XResp.pack(200,"发送成功","");
        }else {
           return XResp.pack(500,"发送失败","");
        }
    }


    @GetMapping("/book/findByBookid/{id}")
    public XJson findOne(@PathVariable Integer id){
        Book one = bookService.findOne(id);
        return XResp.pack(200,"",one);
    }

    @GetMapping("/book/findNewBook/{num}")
    public XJson findNewBook(@PathVariable Integer num){
        if(num < 10) num = 10;
        List<Book> topSale = bookService.findNewBook(num);
        return XResp.pack(200,"",topSale);
    }

    @GetMapping("/book/findSalenum/{num}")
    public XJson findSalenum(@PathVariable Integer num){
        if(num < 5) num = 5;
        List<Book> topSale = bookService.findTopSale(num);
        return XResp.pack(200,"",topSale);
    }

    @GetMapping("/rate/findByBookid/{bookid}/{pagenum}/{lines}")
    public XJson findByBookid(@PathVariable("bookid")Integer bookid,
                              @PathVariable("pagenum")Integer pagenum,
                              @PathVariable("lines")Integer lines){
        if(pagenum < 1) pagenum = 1;
        if(lines < 2) lines = 2;
        List<Comment> coms = commentService.findByid(bookid, null, pagenum, lines);
        int total = commentService.total(bookid, null);
        HashMap<String,Object> map = new HashMap<>();
        map.put("comments",coms);
        map.put("total"   ,total);
        return XResp.pack(200,"",map);
    }



    //评论
    @PostMapping("/rate/add/{bookid}")
    public XJson add(@PathVariable("bookid")Integer bookid
                    ,String content
                    ,Integer rate
                    ,HttpServletRequest request){
        XUser x = (XUser) TokenAndUser.ifToken(request).getData();
        Comment comment = new Comment();
        comment.getBook().setId(bookid);
        comment.setContent(content);
        comment.setRate(rate);
        comment.setTpost(new Date());
        comment.getMyUser().setId(x.getId());
        comment.getMyUser().setNickname(x.getNickname());
        comment.getMyUser().setImg(x.getImg());
        commentService.add(comment);
        return XResp.pack(200,"评论成功",null);
    }
    //添加商品到购物车
    @GetMapping("/addCart/{bookid}")
    public XJson addCart(@PathVariable int bookid
                        , HttpServletRequest request){
        System.out.println(bookid);
        XUser x = (XUser) TokenAndUser.ifToken(request).getData();
        System.out.println(x);
        Book one = bookService.findOne(bookid);
        System.out.println(one);
        if(one == null) return XResp.pack(501,"没有这本书",null);
        Cart cart = new Cart();
        cart.getMyUser().setId(x.getId());
        cart.getBook().setId(one.getId());
        cart.setNum(1);     //数量默认为--1
        cart.setPrice(one.getPrice());
        //添加购物车  -- 有这本书有异常直接修改数量和价格
        int add = cartService.add(cart);
        return XResp.pack(200,"加入购物车......",null);
    }
    //搜索
    @PostMapping("/book/findPageKey/{start}/{num}")
    public XJson findBookIf(
            String key,
            @PathVariable("start")Integer start,
            @PathVariable("num") Integer num){
        if ( start == null || start<1 ) start = 1;
        int count = bookService.count("%" + key + "%");
        List<Book> list = bookService.findPageKey(start, num , "%" + key + "%" );
        for(Book b : list){
            //创建一个正则表达式，不区分大小写
            Pattern pattern = Pattern.compile(key,Pattern.CASE_INSENSITIVE);
            Matcher name = pattern.matcher(b.getName());
            while (name.find()){
                //找到以后添加样式
                b.setName(name.replaceAll("<span style='color:red'>$0</span>"));
            }
            Matcher info = pattern.matcher(b.getInfo());
            while (info.find()){
                //找到以后添加样式
                b.setInfo(info.replaceAll("<span style='color:red'>$0</span>"));
            }
            Matcher maker = pattern.matcher(b.getMaker());
            while (maker.find()){
                //找到以后添加样式
                b.setMaker(maker.replaceAll("<span style='color:red'>$0</span>"));
            }
            Matcher author = pattern.matcher(b.getAuthor());
            while (author.find()){
                //找到以后添加样式
                b.setAuthor(author.replaceAll("<span style='color:red'>$0</span>"));
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("books",list);
        map.put("count",count);
        return XResp.pack(200,"",map);
    }

    @GetMapping("/findPageBook/{start}/{num}/{typeid}")
    public XJson findPages_book(@PathVariable("start") Integer start,
                                @PathVariable("num")Integer num,
                                @PathVariable("typeid")Integer typeid){
        if ( start == null || start<1 ) start = 1;
        if (num == null || num < 2)num = 2;
        int total = bookService.total(typeid);
        List<Book> list = bookService.findPageBook(start, num, typeid);
        Map<String,Object> map = new HashMap<>();
        map.put("books",list);
        map.put("total",total);
        return XResp.pack(200,"",map);
    }
    //商品类型
    @GetMapping("/type/findAll2")
    public XJson findType(){
        return XResp.pack(200,"",typeService.findAll());
    }
    //轮播图
    @GetMapping("/findHot/{type}/{num}")
    public XJson findHot(@PathVariable("type") Integer type
                        , @PathVariable("num") Integer num){
        List<Hot> byTypeNum = hotService.findByTypeNum(type, num);
        return XResp.pack(200,"数据查找成功",byTypeNum);
    }
    //图片显示
    @RequestMapping("/showimg/{id}")
    public void showimg(@PathVariable String id
                      , HttpServletResponse response) throws IOException {
        if(id == null) return;
        LargeFile one = largeFileService.findOne(id);
        byte[] buf = (byte[]) one.getContent();
        response.setContentType("image/jpeg");
        response.getOutputStream().write(buf);
        response.flushBuffer();
    }
    //注册
    @PostMapping("/addUser")
    public XJson register(@RequestParam(value = "myimg"
                        , required = false)MultipartFile file
                        , XUser xUser)throws IOException{
              log.info("file=" + file);
              log.info("添加的用户：" + xUser);
                String uuid = UUID.randomUUID().toString();
                uuid = uuid.replace("-","");
              if(file != null && file.getSize() > 0 ){
                  byte[] bytes = file.getBytes();
                  String fileName = file.getOriginalFilename();
                  largeFileService.add(uuid,fileName,bytes);
              }
                xUser.setImg(uuid);

                userService.add(xUser);
                xUser.setPassword("");
                return XResp.pack(200,"注册成功....",xUser);
    }
}
